package com.example.bookstore.security

import com.example.bookstore.exception.TokenException
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * Created by IntelliJ IDEA.
 * User: lvshe
 * Date: 2019/8/13
 * Time: 19:10
 */
@Component
class TokenServiceImpl : TokenService {


    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate

    override fun checkTokenFromSession(key: String, token: String): Boolean {
//        TODO("not implemented")
        return true
    }

    override fun saveTokenToSession(key: String, token: String): Boolean {
//        TODO("not implemented")
        return true
    }

    override fun removeTokenFromSession(key: String, token: String): Boolean {
//        TODO("not implemented")
        return true
    }

    override fun getUserTokensFromSession(key: String, identity: String): Set<String> {
//        TODO("not implemented")
        return emptySet()
    }


    override fun parseUsernameFromToken(request: HttpServletRequest): String? {
        val authorizationHeader = request.getHeader("Authorization")
        if (!authorizationHeader.isNullOrBlank()) {
            val token = authorizationHeader.replace("Bearer", "", true).trim()
            System.err.println(token)
            val claims = Jwts.parser().setSigningKey(TokenService.SECRET).parseClaimsJws(token).body
            val username = claims["username"] as String? ?: throw TokenException("Token  username字段缺失")
            if (!checkTokenFromSession("Token_$username", token)) throw TokenException("服务器 Session 不存在此 Token")
            return username
        }
        return null
    }


    override fun createTokenForUsername(username: String): String {
        val token = Jwts.builder()
                .setExpiration(Date(System.currentTimeMillis() + TokenService.EXPIRED_TIME_MS))
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS256, TokenService.SECRET)
                .compact()
        if (!saveTokenToSession(username, token)) throw TokenException("服务器 Token 储存失败")
        return token
    }


}